package com.unit6;

import java.sql.*;

/**
 * @author 李琦 on 2021/8/16.
 * @version java version "16.0.1" 2021-04-20
 */
public class test2 {
    public static void main(String[] args) {

        Connection conn=null;
        String address = "jdbc:mysql://localhost:3306/data1?useSSL=false&serverTimezone=UTC";
        String dataBaseName="root";
        String dataBasePwd="123456";
        try {

            //加载jdbc驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            //连接数据库
            conn= DriverManager.getConnection(address,dataBaseName,dataBasePwd);
            System.out.println("连接成功!");

            //处理数据
            //编写sql语句
            String sql="select * from stu";
            //Statement对象用来执行sql语句
            Statement stmt=conn.createStatement();
            //执行sql并获取查询结果
            ResultSet rs=stmt.executeQuery(sql);

            while ((rs.next())){
                System.out.print("id: "+rs.getInt("id")+"  ");
                System.out.print("名字: "+rs.getString("name")+"  ");
                System.out.print("年龄: "+rs.getInt("age")+"  ");
                System.out.print("性别: "+rs.getString("sex")+"\n");
            }

        } catch (Exception e) {
            System.out.println("连接失败!");
            e.printStackTrace();
        } finally{
            try {
                conn.close();//关闭连接资源
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
